﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.ServiceModel;
using System.Text;
using System.Threading;
using Raspare;
using Xamarin.Forms;

namespace SharedMobilePlatform
{
    class ShowCharacterPage : TabbedPage
    {
        public static readonly EndpointAddress EndPoint = new EndpointAddress("http://wcf.raspare.se/WcfRaspare.svc");

        protected WcfRaspareClient _client;

        public Karaktär Character;

        protected override bool OnBackButtonPressed()
        {
            Application.Current.Properties["Character"] = null;

            return base.OnBackButtonPressed();
        }

        public ShowCharacterPage(Karaktär character)
            : base()
        {
            BasicHttpBinding binding = CreateBasicHttp();
            _client = new WcfRaspareClient(binding, EndPoint);
            InitializeWcfServiceClient();

            this.Character = character;
            this.Children.Add(new InfoPage(character));
            this.Children.Add(new AbilityPage(character));
            this.Children.Add(new KrokarPage(character.Namn));
            this.Children.Add(new HistoryPage());
        }


        public ShowCharacterPage(string dekaederCharacterNamn)
            : base()
        {
            
            BasicHttpBinding binding = CreateBasicHttp();
            _client = new WcfRaspareClient(binding, EndPoint);
            InitializeWcfServiceClient();
            Character = new Karaktär();
            if (Application.Current.Properties.ContainsKey("Character") && Application.Current.Properties["Character"] != null)
            {
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Character.GetType());
                using (StringReader textReader = new StringReader((string)Application.Current.Properties["Character"]))
                {
                    Character = (Karaktär)x.Deserialize(textReader);
                }
                this.Children.Add(new InfoPage(Character));
                this.Children.Add(new AbilityPage(Character));
                this.Children.Add(new KrokarPage(Character.Namn));
                this.Children.Add(new HistoryPage());
                
            }
            else
            {
                _client.GetWikiSiteAsync(dekaederCharacterNamn);
            }
        }

        private void GetCharacterCompleted(object sender, GetWikiSiteCompletedEventArgs e)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                if (!e.Cancelled)
                {
                    try
                    {                
                        Character = e.Result;
                        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Character.GetType());
                        using (StringWriter textWriter = new StringWriter())
                        {
                            x.Serialize(textWriter, Character);
                            Application.Current.Properties["Character"] = textWriter.ToString();
                        }
                        this.Children.Add(new InfoPage(Character));
                        this.Children.Add(new AbilityPage(Character));
                        this.Children.Add(new KrokarPage(Character.Namn));
                        this.Children.Add(new HistoryPage());
                    }
                    catch (TargetInvocationException)
                    {
                        DisplayAlert("Får ingen kontakt med servern", "Servern svarar inte just nu, försök igen senare.", "OK");
                        Navigation.PopAsync();
                    }
                }
            });
        }

        public void InitializeWcfServiceClient()
        {
            
            _client.GetWikiSiteCompleted += GetCharacterCompleted;
        }

        private static BasicHttpBinding CreateBasicHttp()
        {
            BasicHttpBinding binding = new BasicHttpBinding
            {
                Name = "basicHttpBinding",
                MaxBufferSize = 2147483647,
                MaxReceivedMessageSize = 2147483647
            };
            TimeSpan timeout = new TimeSpan(0, 2, 30);
            binding.SendTimeout = timeout;
            binding.OpenTimeout = timeout;
            binding.ReceiveTimeout = timeout;
            return binding;
        }

        internal void AddToHistory(string diceRoll)
        {
            foreach (ContentPage page in Children)
            {
                if (page is HistoryPage)
                {
                    (page as HistoryPage).AddDiceRoll(diceRoll);
                }
            }
        }
    }
}
